<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\service\UserToken;
use app\api\validate\AddressValidate;
use app\api\service\Token as TokenService;
use app\api\model\UserAddress as UserAddressModel;

class Address extends Common
{
    /**
     * 增加前置方法
     * 调用edit、userAddress方法前，需要调用checkPrimaryScope方法
     * @var array
     */
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => ['edit', 'userAddress']]
    ];

    /**
     * 获取用户收货地址
     * @return \think\response\Json
     * @throws \app\lib\exception\ThrowError
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserAddress()
    {
        $uid = UserToken::getCurrentUid();
        $userAddress = UserAddressModel::where('user_id', $uid)
            ->find();

        if (empty($userAddress))
        {
            T(501001);
        }
        return $this->response($userAddress);
    }

    /**
     * 编辑用户收货地址  新增或编辑
     * @return \think\response\Json
     * @throws \app\lib\exception\ThrowError
     * @throws \think\Exception
     */
    public function edit()
    {
        // 校验参数
        $validate = new AddressValidate('edit');
        $validate->goCheck();

        // 根据Token获取用户的uid
        $uid = TokenService::getCurrentUid();
//        $uid = 59;
        // 根据uid获取用户信息
        $userInfo = UserModel::get($uid);

        if (!$userInfo)
        {
            T(100002);
        }

        // 根据uid获取用户的地址信息，判断是新增还是更新
        $dataArr = $validate->getDataByRule();
        $address = $userInfo->address;

        if (!$address)
        {
//            $dataArr['user_id'] = $uid;
//            UserAdressModel::create($dataArr);
            // 因为没有address属性，所以要用address()方法来save
            $userInfo->address()->save($dataArr);
        }
        else
        {
//            $dataArr['user_id'] = $uid;
//            UserAdressModel::update($dataArr, $uid);
            $userInfo->address->save($dataArr);
        }

        return $this->response();
    }
}
